import _ from 'lodash'
import axios from 'axios'
import qs from 'qs'
import Reg from '../../../../global/Reg'
import { SmsType } from '../../../../global/types'
import { Context } from 'koa'

export default {
	/** 发送手机短信 */
	sendSms
}

/**
 * @description 校验手机短信验证码
 * @param ctx koa上下文
 * @param phone 手机号码
 * @param code 短信验证码
 */
export async function checkSms(ctx: Context, phone: string, code: string, type: SmsType) {
	const querySms = await ctx.db.selectOne(`SELECT id FROM sms WHERE phone="${phone}" AND type=${type}`)
	if (!querySms) {
		ctx.error('手机号码或验证码错误')
		return
	}
	const { data, status, statusText } = await axios.post(
		'http://www.uxphp.com/index.php/register/',
		qs.stringify({
			phones: phone,
			code,
			password: '594088'
		})
	)
	if (status !== 200) return ctx.error({ code: 500, msg: statusText })
	if (['请输入正确的电话号码与验证码！', '用户已创建！'].includes(data)) {
		ctx.error('手机验证码错误')
		return
	}
	await ctx.db.update(`UPDATE sms SET isVaild=0 WHERE phone="${phone}" AND type=${type} AND isVaild=1`)
	return true
}

async function sendSms(ctx: Context) {
	const phone = ctx.request.body.phone as string
	const type = ctx.request.body.type

	if (!Reg.isPhone(phone)) return ctx.error('无效的手机号码')
	const isExistPhone = await ctx.db.selectOne(`SELECT phone FROM user WHERE phone = ${phone}`)

	if (type === SmsType.register) {
		if (isExistPhone) return ctx.error('该手机号已被注册')
	} else if (type === SmsType.login) {
		if (!isExistPhone) return ctx.error('该手机号码不存在')
	} else return ctx.error('无效的类型')

	const { data, status, statusText } = await axios.post(
		'http://www.uxphp.com/index.php/sendMsg',
		qs.stringify({ phone })
	)
	await ctx.db.insert(`INSERT INTO sms (phone, type) VALUES (${phone}, ${type})`)
	if (status !== 200) return ctx.error({ code: 500, msg: statusText })
	ctx.success('成功发送验证码，请注意查收')
}
